package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRegisterVo;
import com.atguigu.gulimall.auth.feign.MemberFeignServise;
import com.atguigu.gulimall.auth.feign.ThirdPartyFeignService;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegistVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/sms")
public class LoginController {

    @Autowired
    private ThirdPartyFeignService thirdPartyFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MemberFeignServise memberFeignServise;

    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute != null){
            return "redirect:http://gulimall.com";
        }else {
            return "http:/login.html";
        }
    }

    @ResponseBody
    @GetMapping("/sendcode")
    public R sendCode(@RequestParam("mobilePhone") String mobilePhone) {

        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_PREFIX + mobilePhone);
        if (!StringUtils.isEmpty(redisCode)) {
            long codeTime = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - codeTime < 60000) {
                //60秒内不能重复发送
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        String code = UUID.randomUUID().toString().substring(0, 5);
        String subString = UUID.randomUUID().toString().substring(0, 5) + "_" + System.currentTimeMillis();
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_PREFIX + mobilePhone, subString, 10, TimeUnit.MINUTES);
        thirdPartyFeignService.sendCode(mobilePhone, code);

        return R.ok();
    }

    @PostMapping("/regist")
    public String register(@Valid @RequestBody UserRegistVo registVo, BindingResult result, RedirectAttributes model) {

        //校验请求参数
        if (result.hasErrors()) {
            Map<String, String> map = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            model.addFlashAttribute("error", map);
            return "redirect:http://gulimall.com/reg.html";
        }

        //校验前段传过来的验证码
        String code = registVo.getCode();
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_PREFIX + registVo.getMobilePhone());
        if (!StringUtils.isEmpty(redisCode)) {
            if (code.equalsIgnoreCase(redisCode.split("_")[0])) {
                //删除验证码
                redisTemplate.delete(AuthServerConstant.SMS_CODE_PREFIX + registVo.getMobilePhone());
                //验证码校验通过,调用会员服务进行保存数据
                R r = memberFeignServise.regist(registVo);
                if (r.getCode() == 0) {
                    return "http:/login.html";
                } else {
                    Map<String, String> map = new HashMap();
                    map.put("msg", r.getDate("msg", new TypeReference<String>() {
                    }));
                    model.addFlashAttribute("error", map);
                    return "redirect:http://gulimall.com/reg.html";
                }

            } else {
                Map<String, String> map = new HashMap();
                map.put("error", "验证码错误");
                model.addFlashAttribute("error", map);
                return "redirect:http://gulimall.com/reg.html";
            }
        } else {
            Map<String, String> map = new HashMap();
            map.put("error", "验证码错误");
            model.addFlashAttribute("error", map);
            return "redirect:http://gulimall.com/reg.html";
        }
    }

    @PostMapping("/login")
    public String login(@RequestBody UserLoginVo loginVo, RedirectAttributes attributes, HttpSession session) {


        R r = memberFeignServise.login(loginVo);
        if (r.getCode() == 0) {
            MemberRegisterVo data = r.getDate("data", new TypeReference<MemberRegisterVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER,data);
            return "redirect:http://gulimall.com";
        } else {
            Map<String, String> map = new HashMap();
            map.put("error", r.getDate("msg", new TypeReference<String>() {
            }));
            attributes.addFlashAttribute("error",map);
            return "http:/login.html";
        }
    }
}
